package com.sys.web.controller;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.sys.constant.UploadAndDownloadPath;
import com.sys.service.UploadOperationSer;
import com.sys.service.impl.UploadOperationImpl;

@WebServlet("/file")
@MultipartConfig
public class FileOperation extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String operation = request.getParameter("operation");
		if(operation.equals("up")) {
			try {
				upload(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}else if(operation.equals("down")) {
			download(request, response);
		}
	}

	

	private void download(HttpServletRequest request, HttpServletResponse response) {
		
	}

	private void upload(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException, SQLException {
		//Return a collection of all uploaded Parts
		Collection<Part> parts = request.getParts();
		Iterator<Part> iterator = parts.iterator();
		UploadOperationSer uOS = new UploadOperationImpl();
		String uper = (String)request.getSession().getAttribute("user");
		Integer uploadSuccessNum = 0;
		while(iterator.hasNext()) {
			Part part = iterator.next();
			String header = part.getHeader("content-disposition");
			//得到真实文件名
			String fileName = uOS.getFileName(header);
			if(!uOS.isFileNameHasExisted(uper+fileName)) {
				//写入服务器
				String wholePath = UploadAndDownloadPath.path+File.separator+uper+fileName;
				part.write(wholePath);
				//上传记录插入数据库
				uOS.addUpload(uper+fileName, uper,  uOS.getFileSize(wholePath), uOS.getCurrentDate());
				uploadSuccessNum++;
			}
		}
		//成功上传的个数
		request.setAttribute("uploadSuccessNum", uploadSuccessNum);
		response.sendRedirect(request.getContextPath()+"\\myHomeUI");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	

}